package com.builder.settings;

import com.builder.settings.interfaces.HelperStorage;
import com.builder.utils.AutoCompleteTextField;
import com.builder.utils.AutoCompleteTextField.Java2sAutoComboBox.AutoTextFieldEditor;
import java.awt.Component;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellEditor;

/**
 * @author sad
 */
public class PropertyCellEditor extends AbstractCellEditor implements TableCellEditor {

    private AutoCompleteTextField.Java2sAutoComboBox editor;
    private JTable table;
    public PropertyCellEditor(HelperStorage helperStorage,final JTable table) {
        this.table=table;
        editor = new AutoCompleteTextField.Java2sAutoComboBox(helperStorage.getAllKeysForAutocomplete()).setStrict(false);
        ((AutoTextFieldEditor)editor.getEditor()).getEditorComponent().addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    fireEditingStopped();
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            int row=table.getSelectedRow();
                            int column=table.getSelectedColumn();
                            row++;
                            if(row>=table.getRowCount()){
                                row--;
                            }
                            table.setRowSelectionInterval(row, row);
                            table.editCellAt(row, column);
                            SwingUtilities.invokeLater(new Runnable() {

                                @Override
                                public void run() {
                                    ((AutoTextFieldEditor)editor.getEditor()).getEditorComponent().requestFocus();
                                }
                            });
                            
                        }
                    });
                }
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    fireEditingCanceled();
                }
            }
        });
    }

    @Override
    public Object getCellEditorValue() {
        return editor.getSelectedItem();
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        editor.setSelectedItem(value);
        return editor;
    }

}
